package com.cn.yds.bdy.service.ipml;

import com.cn.yds.bdy.dao.UserRepository;
import com.cn.yds.bdy.dao.model.UserModel;
import com.cn.yds.bdy.service.UserService;
import com.cn.yds.bdy.vo.UserProfileVo;
import com.cn.yds.bdy.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserModel getUserByLoginIdAndPw(UserVo userVo) {

        String password = DigestUtils.md5DigestAsHex(userVo.getPassword().getBytes());
        log.info("password is {}", password);
        UserModel userModel = userRepository.findByLoginIdAndPasswordAndRoleAndStatus(userVo.getAccount(),
                password, userVo.getRole(), 1);
        return userModel;
    }

    @Override
    public int updateUserInfo(UserProfileVo userProfileVo) {
        UserModel userModel   = userRepository.findByLoginId(userProfileVo.getLoginId());
        if (userModel == null) {
            return 0;
        }

        userModel.setName(userProfileVo.getName());
        userModel.setPassword(userProfileVo.getPassword());
        userModel.setAcademy(userProfileVo.getAcademy());
        userModel.setGender(userProfileVo.getGender());
        userModel.setTel(userProfileVo.getTel());
        userModel.setDescription(userProfileVo.getDescription());
        if (userModel.getRole() == 1 ){
            userModel.setMajor(userProfileVo.getMajor());
            userModel.setGrade(userProfileVo.getGrade());
        }else{
            userModel.setResearchDirection(userProfileVo.getResearchDirection());
            userModel.setAcademicTitle(userProfileVo.getAcademicTitle());
        }

        userRepository.save(userModel);
        return 1;
    }

    @Override
    public UserModel getUserByLoginId(String loginId) {
        Assert.isTrue(!StringUtils.isEmpty(loginId),"Login id is not empty.");
        return userRepository.findByLoginId(loginId);
    }

    @Override
    public UserModel getUserById(Integer id) {

        return userRepository.findById(id).orElse(null);
    }


}
